package com.shujia.spark

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

import scala.util.Random

object Demo15PI {
  def main(args: Array[String]): Unit = {


    val conf: SparkConf = new SparkConf()
      .setAppName("pi")
      .setMaster("local")

    val sc = new SparkContext(conf)


    //scala 快速生成固定长度的集合
    val list = 0 to 100000000


    val rdd1: RDD[Int] = sc.parallelize(list)


    //随机生成点
    val pointRDD: RDD[(Double, Double)] = rdd1.map(i => {


      //模拟生成正方形中的点
      // x (-1,1)  y (-1,1)
      val x: Double = Random.nextDouble() * 2 - 1
      val y: Double = Random.nextDouble() * 2 - 1

      (x, y)
    })


    //计算圆内点的数量
    val yuanRDD: RDD[(Double, Double)] = pointRDD.filter {
      case (x, y) => {
        x * x + y * y <= 1
      }
    }

    val pi: Double = yuanRDD.count().toDouble / pointRDD.count() * 4


    println("pi=" + pi)


  }

}
